<?php

namespace App\Controllers;

use App\Libraries\TimeHelper;
use App\Libraries\InputCleaner;
use App\Libraries\PasswordVerify;
use App\Libraries\EmailService;

use App\Models\WebModel;
use App\Models\SidebarModel;

use App\Models\PanelModel;
use App\Models\FavouriteModel;
use App\Models\BannerModel;
use App\Models\HomeSectionsModel;
use App\Models\CategoryModel;
use App\Models\CountriesModel;
use App\Models\PodcastModel;
use App\Models\RadioViewsModel;
use App\Models\RadioModel;
use App\Models\SubscriptionModel;
use App\Models\ReportsModel;
use App\Models\SuggestModel;
use App\Models\RatingModel;
use App\Models\UsersModel;
use App\Models\ActiveLogModel;
use App\Models\EpisodeModel;
use App\Models\NotificationModel;

class ApiWebController extends BaseController {
    
    protected $apiHeader;

    public function __construct(){
        $this->apiHeader = getenv('API_HEADER_WEB');
        $panelModel = new PanelModel();
        $this->settings = $panelModel->getSettings();
    }

    public function index() {

        $action = $this->request->getPost('helper_name') ?? $this->request->getGet('helper_name') ?? '';
        if (empty($action)) {
            return $this->sendResponse(['MSG' => 'Directory access is forbidden.', 'success' => '0']);
        }
        
        if($action == "web_details"){
            return $this->getWebDetails();
        } else if($action == "get_home"){
            return $this->getHome();
        } else if($action == "get_sidebar"){
            return $this->getSidebar();
        } else if($action == "get_radios"){
            return $this->getRadios();
        } else if($action == "get_category"){
            return $this->getCategory();
        } else if($action == "get_countries"){
            return $this->getCountries();
        } else if($action == "get_podcasts"){
            return $this->getPodcasts();
        } else if($action == "get_cat_radio"){
            return $this->getCatRadio();
        } else if($action == "get_countries_radio"){
            return $this->getCountriesRadio();
        } else if($action == "get_banner_radio"){
            return $this->getBannerRadio();
        } else if($action == "get_single_radio"){
            return $this->getSingleRadio();
        } else if($action == "get_podcast_by"){
            return $this->getPodcastBy();
        } else if($action == "get_search_radio"){
            return $this->getSearchRadio();
        } else if($action == "user_login"){
            return $this->userLogin();
        } else if($action == "user_login"){
            return $this->userLogin();
        } else if($action == "user_register"){
            return $this->userRegister();
        } else if($action == "post_suggest"){
            return $this->addSuggest();
        } else if($action == "clear_notification"){
            return $this->clearNotification();
        } else if($action == "get_notification"){
            return $this->getNotification();
        } else if($action == "profile_update"){
            return $this->profileUpdate();
        } else {
           return $this->sendResponse(['MSG' => 'Directory access is forbidden.', 'success' => '0']);
        }
    }
    private function profileUpdate() {
        
        $user_id = $this->request->getPost('user_id') ?? $this->request->getGet('user_id') ?? '';
        $user_email = $this->request->getPost('user_email') ?? $this->request->getGet('user_email') ?? '';
        $user_name = $this->request->getPost('user_name') ?? $this->request->getGet('user_name') ?? '';
        $user_phone = $this->request->getPost('user_phone') ?? $this->request->getGet('user_phone') ?? '';
        $user_gender = $this->request->getPost('user_gender') ?? $this->request->getGet('user_gender') ?? '';
        
        $response = [];

    	$usersModel = new UsersModel();
    	$user = $usersModel->find($user_id);
    	if (!$user) {
    	    $response = ['MSG' => 'User not found', 'success' => '0'];
    	} else if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
    	    $response = ['MSG' => 'Email format is invalid!', 'success' => '0'];
    	} else if ($user['user_email'] == $user_email && $user['id'] != $user_id) {
    	    $response = ['MSG' => 'Email is not found !', 'success' => '0'];
    	} else {
    	    
    	    $data = [
                'user_name' => InputCleaner::cleanInput($user_name),
                'user_email' => trim($user_email),
                'user_phone' => InputCleaner::cleanInput($user_phone),
            ];
            
            $usersModel->update($user_id, $data);
            
            $response = ['MSG' => 'Updated successfully.', 'success' => '1'];
        }
        return $this->sendResponse($response);
    }
    
    private function profilePasswordUpdate() {
        
        $user_id = $this->request->getPost('user_id') ?? $this->request->getGet('user_id') ?? '';
        $user_password = $this->request->getPost('user_password') ?? $this->request->getGet('user_password') ?? '';
        
        $response = [];

    	$usersModel = new UsersModel();
    	$user = $usersModel->find($user_id);
    	if (!$user) {
    	    $response = ['MSG' => 'User not found', 'success' => '0'];
    	} else {
            if (!empty($user_password)) {
                $hashedPassword = PasswordVerify::hash(trim($user_password));
                $data['user_password'] = $hashedPassword;
                
                $usersModel->update($user_id, $data);
                
                $response = ['MSG' => 'Updated successfully.', 'success' => '1'];
            } else {
                $response = ['MSG' => 'Update error!', 'success' => '0'];
            }
        }
        return $this->sendResponse($response);
    }
    
    private function userRegister() {
        $user_email = $this->request->getPost('user_email') ?? $this->request->getGet('user_email') ?? '';
        $user_name = $this->request->getPost('user_name') ?? $this->request->getGet('user_name') ?? '';
        $user_phone = $this->request->getPost('user_phone') ?? $this->request->getGet('user_phone') ?? '';
        $user_gender = $this->request->getPost('user_gender') ?? $this->request->getGet('user_gender') ?? '';
        $user_password = $this->request->getPost('user_password') ?? $this->request->getGet('user_password') ?? '';
        $user_id = '';
        
        $usersModel = new UsersModel();
        
        $user = $usersModel->where('user_email', $user_email)->first();
        if ($user) {
            $response = ['MSG' => 'Email is already exist !', 'success' => '0'];
        } else {
            
            $imageName = '';
            $hashedPassword = PasswordVerify::hash(trim($user_password));
            
            $data = [
                'user_name' => addslashes(trim($user_name)),
                'user_email' => addslashes(trim($user_email)),
                'user_phone' => addslashes(trim($user_phone)),
                'user_password' => $hashedPassword,
                'user_gender'  => addslashes(trim($user_gender)),
                'registered_on'  =>  strtotime(date('d-m-Y h:i:s A')),
                'profile_img' => $imageName,
                'status'  =>  '1'
            ];
            
            $usersModel->insert($data);
            $user_id = $usersModel->getInsertID();
            
            $webModel = new WebModel();
            $dataSite = $webModel->getSettings();
            
            $emailService = new EmailService();
            $toName   = 'Recipient Register';
            $subject = '[IMPORTANT] '.$dataSite['site_name'].' Registration Successful';
            $msg  = '<tr>
        		<img src="'.base_url('images/'.$dataSite['web_logo_1']).'" alt="header" />
        		</br>
        		<h1>Hello! '.$user_name.'</h1>
        		<p>Your registration is successfully completed</p>
        		<p>Thank you.</p>
        		';
            if ($emailService->sendEmail($email, $toName, $subject, $msg)) {
                
            }
            
            $response = ['MSG' => 'Registration successfully.', 'success' => '1'];
            $this->updateActivityLog($user_id);
        }
        
        return $this->sendResponse($response);
    }
    
    private function clearNotification() {
        $user_id = $this->request->getPost('user_id') ?? $this->request->getGet('user_id') ?? '';
        
        if (empty($user_id)) {
            return $this->sendResponse(['MSG' => 'User ID is required.', 'success' => '0']);
        }
        
        $notificationModel = new NotificationModel();
        $notificationModel->where('user_id', $user_id)->delete();
        
        return $this->sendResponse(['MSG' => 'Notification clear successfully.', 'success' => '1']);
    }
    
    private function addSuggest() {
        
        $user_id = $this->request->getPost('user_id') ?? $this->request->getGet('user_id') ?? '';
        $suggest_title = $this->request->getPost('suggest_title') ?? $this->request->getGet('suggest_title') ?? '';
        $suggest_message = $this->request->getPost('suggest_message') ?? $this->request->getGet('suggest_message') ?? '';
        
        $data = array(
            'user_id'  =>  $user_id,
            'suggest_title'  =>  $suggest_title,
            'suggest_image'  =>  '',
            'suggest_message'  =>  $suggest_message,
            'suggest_on'  =>  strtotime(date('d-m-Y h:i:s A')), 
        );
        $suggest = new SuggestModel();
        $suggest->insert($data);
        
        // Insert Notification
        $notification_data = [
            'user_id'            => $user_id,
            'notification_title' => 'Suggest Submitted',
            'notification_msg'   => $suggest_message,
            'notification_on'    => strtotime(date('d-m-Y h:i:s A')) 
        ];
        $notification = new NotificationModel();
        $notification->insert($notification_data);
        
        return $this->sendResponse(['MSG' => 'Suggest submitted successfully.', 'success' => '1']);
    }
    
    private function getNotification() {
        $user_id = $this->request->getPost('user_id') ?? $this->request->getGet('user_id') ?? '';
        
        $model = new NotificationModel();
        $result = $model->where('user_id', $user_id)->orderBy('id', 'DESC')->findAll(); 
        if (!empty($result)) {
            $row = $this->getNotificationList($result);
            return $this->sendResponse($row);
        }
        return $this->sendResponse([]);
    }
    
    private function userLogin() {
        
        $email = $this->request->getPost('user_email') ?? $this->request->getGet('user_email') ?? '';
        $password = $this->request->getPost('user_password') ?? $this->request->getGet('user_password') ?? '';
        
        
        $validation = \Config\Services::validation();
        $validation->setRules([
            'email' => 'required|valid_email',
        ]);
        
        if (!$validation->run(['email' => $email])) {
            $response=array('MSG' => 'Email format is invalid !','success'=>'0');
            return $this->sendResponse($response);
        }
        
        $usersModel = new UsersModel();
        
        $user = $usersModel->where('user_email', $email)
                ->groupStart()
                ->where('LOWER(user_type)', 'normal')
                ->groupEnd()
                ->where('id !=', 0)
                ->first();
                
        if ($user) {
            if ($user['status'] == 1) {
                // Check if password matches
                
                if (PasswordVerify::verify($password, $user['user_password'])) {
                    // Update activity log
                    $this->updateActivityLog($user['id']);
                    
                    // Return response with user details
                    $response = [
                        'user_id'    => $user['id'],
                        'user_name'  => $user['user_name'],
                        'user_phone' => !empty($user['user_phone']) ? $user['user_phone'] : '',
                        'user_email' => !empty($user['user_email']) ? $user['user_email'] : '',
                        'user_gender'=> $user['user_gender'],
                        'profile_img'=> base_url('images/' . $user['profile_img']),
                        'MSG'        => 'Login successfully.',
                        'success'    => '1'
                    ];
                } else {
                    // Invalid password
                    $response = ['MSG' => 'Password is invalid !', 'success' => '0'];
                }
            } else {
                // Account deactivated
                $response = ['MSG' => 'Sorry ! Your account is suspended', 'success' => '0'];
            }
        } else {
            // Email not found
            $response = ['MSG' => 'Email is not found !', 'success' => '0'];
        }
        return $this->sendResponse($response);
    }
    
    private function getSearchRadio() {
        
        $search_text = $this->request->getPost('search_text') ?? $this->request->getGet('search_text') ?? '';
        
        $radioModel = new RadioModel();
        
        $result = $radioModel->select('tbl_radio.*, tbl_category.category_name')
                ->join('tbl_category', 'tbl_radio.cat_id = tbl_category.cid', 'left')
                ->like('tbl_radio.radio_title', $search_text)
                ->where('tbl_radio.status', 1)
                ->where('tbl_category.status', 1)
                ->orderBy('tbl_radio.radio_title', 'DESC')
            ->findAll();
            
        $row = $this->getRadioList($result);
        return $this->sendResponse($row);
    }
    
    private function getPodcastBy() {
        
        $podcastId = $this->request->getPost('podcast_id') ?? $this->request->getGet('podcast_id') ?? '0';
        
        $model = new EpisodeModel();
        $result = $model->select('tbl_episode.id, tbl_episode.podcast_id, tbl_episode.episode_title, tbl_episode.episode_url, tbl_podcast.podcast_name, tbl_podcast.podcast_image')
            ->join('tbl_podcast', 'tbl_episode.podcast_id = tbl_podcast.pid', 'left')
            ->where('tbl_episode.podcast_id', $podcastId)
            ->where('tbl_episode.status', '1')
            ->orderBy('tbl_episode.id', 'DESC')
            ->findAll();
        if (!empty($result)) {
            $row = $this->getEpisodeList($result);
            return $this->sendResponse($row);
        }
        return $this->sendResponse([]);
    }
    
    private function getBannerRadio() {
        
        $banner_id = $this->request->getPost('banner_id') ?? $this->request->getGet('banner_id') ?? '0';
        
        // Load Banner Model
        $bannerModel = new BannerModel();
        $banner = $bannerModel->select('banner_post_id')->where('status', '1')->where('bid', $banner_id)->orderBy('bid', 'DESC')->first();
        if (!empty($banner)) {
            $radio_ids = trim($banner['banner_post_id']);
            if (!empty($radio_ids)) {
                // Load Radio Model
                $radioModel = new RadioModel();
                
                $result = $radioModel->select('tbl_radio.id, tbl_radio.cat_id, tbl_radio.radio_title, tbl_radio.radio_url, tbl_radio.radio_image, tbl_radio.rate_avg, tbl_radio.total_rate, tbl_radio.total_views, tbl_radio.isPremium, tbl_category.category_name')
                    ->join('tbl_category', 'tbl_radio.cat_id = tbl_category.cid', 'left')
                    ->whereIn('tbl_radio.id', explode(',', $radio_ids))
                    ->where('tbl_radio.status', '1')
                    ->where('tbl_category.status', '1')
                    ->orderBy('tbl_radio.id', 'DESC')
                    ->findAll();
                    
                $row = $this->getRadioList($result);
                return $this->sendResponse($row);
            }
        }
        return $this->sendResponse([]);
    }
    
    private function getCatRadio() {
        
        $cat_id = $this->request->getPost('cat_id') ?? $this->request->getGet('cat_id') ?? '0';
        
        $model = new RadioModel();
            
        $result = $model->select('tbl_radio.id, tbl_radio.cat_id, tbl_radio.radio_title, tbl_radio.radio_url, tbl_radio.radio_image, tbl_radio.rate_avg, tbl_radio.total_rate, tbl_radio.total_views, tbl_radio.isPremium, tbl_category.category_name')
            ->join('tbl_category', 'tbl_radio.cat_id = tbl_category.cid', 'left')
            ->where('tbl_radio.cat_id', $cat_id)
            ->where('tbl_radio.status', '1')
            ->where('tbl_category.status', '1')
            ->orderBy('tbl_radio.id', 'DESC')
            ->findAll();
            
        $row = $this->getRadioList($result);
        return $this->sendResponse($row);
    }
    
    private function getCountriesRadio() {
        
        $countries_id = $this->request->getPost('countries_id') ?? $this->request->getGet('countries_id') ?? '0';
        
        $model = new RadioModel();
            
        $result = $model->select('tbl_radio.id, tbl_radio.cat_id, tbl_radio.radio_title, tbl_radio.radio_url, tbl_radio.radio_image, tbl_radio.rate_avg, tbl_radio.total_rate, tbl_radio.total_views, tbl_radio.isPremium, tbl_category.category_name')
            ->join('tbl_category', 'tbl_radio.cat_id = tbl_category.cid', 'left')
            ->where('tbl_radio.countries_id', $countries_id)
            ->where('tbl_radio.status', '1')
            ->where('tbl_category.status', '1')
            ->orderBy('tbl_radio.id', 'DESC')
            ->findAll();
            
        $row = $this->getRadioList($result);
        return $this->sendResponse($row);
    }
    
    private function getHome() {
        $bannerModel = new BannerModel();
        $dataBanner = $bannerModel->orderBy('bid', 'DESC')->where('status', 1)->findAll();
        $row['slider'] = $this->getBannerList($dataBanner);
        
        $countriesModel = new CountriesModel();
        $countriesResult = $countriesModel->where('status', 1)->orderBy('sid', 'DESC')->limit(15)->findAll();
        $row['countries_list'] = $this->getCountriesList($countriesResult);
        
        $radioModel = new RadioModel();
        $latestRadios = $radioModel->getLatestRadio(16);
        $row['recently_radio'] = $this->getRadioList($latestRadios);
        
        return $this->sendResponse($row);
    }
    
    private function getRadios() {
        $radioModel = new RadioModel();
        $result = $radioModel->getLatestRadio(null);
        $row = $this->getRadioList($result);
        return $this->sendResponse($row);
    }

    private function getCategory() {
        $categoryModel = new CategoryModel();
        $result = $categoryModel->where('status', 1)->orderBy('cid', 'DESC')->findAll();
        $row = $this->getCategoryList($result);
        return $this->sendResponse($row);
    }
    
    private function getCountries() {
        $countriesModel = new CountriesModel();
        $result = $countriesModel->where('status', 1)->orderBy('sid', 'DESC')->findAll();
        $row = $this->getCountriesList($result);
        return $this->sendResponse($row);
    }
    
    private function getPodcasts() {
        $podcastModel = new PodcastModel();
        $result = $podcastModel->where('status', 1)->orderBy('pid', 'DESC')->findAll();
        $row = $this->getPodcastsList($result);
        return $this->sendResponse($row);
    }
    
    private function getSingleRadio() {
        
        $radioId = $this->request->getPost('radio_id') ?? $this->request->getGet('radio_id') ?? '0';
        
        $radioModel = new RadioModel();
        $result = $radioModel
            ->select('tbl_radio.id, tbl_radio.cat_id, tbl_radio.radio_title, tbl_radio.radio_url, tbl_radio.radio_image, 
                     tbl_radio.rate_avg, tbl_radio.total_rate, tbl_category.category_name, tbl_radio.total_views, tbl_radio.isPremium, tbl_radio.radio_description')
            ->join('tbl_category', 'tbl_radio.cat_id = tbl_category.cid')
            ->where('tbl_radio.id', $radioId)
            ->where('tbl_radio.status', 1)
            ->where('tbl_category.status', 1)
            ->orderBy('tbl_radio.id', 'DESC')
            ->findAll();
            
        $row['radio_list'] = $this->getRadioListSingle($result);
        
        $radioModel2 = new RadioModel();
        $result2 = $radioModel2
            ->select('tbl_radio.id, tbl_radio.cat_id, tbl_radio.radio_title, tbl_radio.radio_url, tbl_radio.radio_image, 
                     tbl_radio.rate_avg, tbl_radio.total_rate, tbl_category.category_name, tbl_radio.total_views, tbl_radio.isPremium')
            ->join('tbl_category', 'tbl_radio.cat_id = tbl_category.cid')
            ->where('tbl_radio.status', 1)
            ->where('tbl_category.status', 1)
            ->orderBy('RAND()', '', false) // raw ORDER BY RAND()
            ->limit(8)
            ->findAll();
            
        $row['similar_list'] = $this->getRadioList($result2);
        
        $ratingModel = new RatingModel();
        $result3 = $ratingModel
        ->select('tbl_rating.id, tbl_rating.post_id, tbl_rating.device_id, tbl_rating.rate, tbl_rating.message, tbl_rating.dt_rate, 
                      tbl_users.user_name, tbl_users.profile_img')
                     
        ->join('tbl_users', 'tbl_rating.device_id = tbl_users.id')
        ->where('post_id', $radioId)->orderBy('id', 'DESC')->findAll();
        
        foreach ($result3 as &$rating) {
            if (!empty($rating['profile_img'])) {
                $rating['profile_img_url'] = base_url('images/'.$rating['profile_img']);
            } else {
                $rating['profile_img_url'] = base_url('assets/images/user_photo.png');
            }
        }
        $row['rating_list'] = $result3;
        
        return $this->sendResponse($row);
    }
    
    // Fetch website details
    private function getWebDetails() {
        $webModel = new WebModel();
        $data = $webModel->getSettings();
        
        if (empty($data)) {
            return $this->sendResponse(['MSG' => 'Directory access is forbidden.', 'success' => '0']);
        }
        
        $jsonObj = [
            'site_name' => $data['site_name'],
            'site_description' => $data['site_description'],
            'site_keywords' => $data['site_keywords'],
            'copyright_text' => $data['copyright_text'],
            'web_logo_1' => base_url('images/'.$data['web_logo_1']),
            'web_logo_2' => base_url('images/'.$data['web_logo_2']),
            'web_favicon' => base_url('images/'.$data['web_favicon']),
            'header_code' => $data['header_code'],
            'footer_code' => $data['footer_code'],
            
            'contact_page_title' => $data['contact_page_title'],
            'address' => $data['address'],
            'contact_number' => $data['contact_number'],
            'contact_email' => $data['contact_email'],
            'android_app_url' => $data['android_app_url'],
            'ios_app_url' => $data['ios_app_url'],
            'facebook_url' => $data['facebook_url'],
            'twitter_url' => $data['twitter_url'],
            'youtube_url' => $data['youtube_url'],
            'instagram_url' => $data['instagram_url'],
            'about_page_title' => $data['about_page_title'],
            'about_content' => $data['about_content'],
            'about_status' => $data['about_status'],
            'privacy_page_title' => $data['privacy_page_title'],
            'privacy_content' => $data['privacy_content'],
            'privacy_page_status' => $data['privacy_page_status'],
            'terms_of_use_page_title' => $data['terms_of_use_page_title'],
            'terms_of_use_content' => $data['terms_of_use_content'],
            'terms_of_use_page_status' => $data['terms_of_use_page_status']
        ];
        return $this->sendResponse($jsonObj);
    }
    
    private function getSidebar() {
        $sidebarModel = new SidebarModel();
        $dataSidebar = $sidebarModel->orderBy('id', 'ASC')->findAll();
        
        if (empty($dataSidebar)) {
            return $this->sendResponse(['MSG' => 'Directory access is forbidden.', 'success' => '0']);
        }
        
        $jsonObj = array_map(function($data) {
            return [
                'id' => $data['id'],
                'sidebar_type' => $data['sidebar_type'],
                'sidebar_title' => $data['sidebar_title'],
                'sidebar_icon' => $data['sidebar_icon'],
                'sidebar_editor' => $data['sidebar_editor'],
                'sidebar_html' => $data['sidebar_html'],
                'sidebar_image' => base_url('images/'.$data['sidebar_image']),
                'sidebar_image_link' => $data['sidebar_image_link'],
            ];
        }, $dataSidebar);
        
        $row['sidebar_list'] = $jsonObj;
        
        $radioModel = new RadioModel();
        $result = $radioModel->getTrendingRadios(5);
        $row['trending_radios'] = $this->getRadioList($result);
        
        return $this->sendResponse($row);
    }

    // Reusable method for sending JSON responses
    private function sendResponse($data) {
        $response = [$this->apiHeader => $data];
        return $this->response->setJSON($response);
    }
    
    // List --------------------------------------------------------------------
    private function getEpisodeList($result){
        $jsonObj = [];
        if (empty($result)) {
           return $jsonObj; 
        }
        foreach ($result as $data) {
            $jsonObj[] = [
                'id'            => $data['id'],
                'podcast_id'    => $data['podcast_id'],
                'episode_title' => $data['episode_title'],
                'episode_url'   => $data['episode_url'],
                'podcast_name'  => $data['podcast_name'],
                'podcast_image' => base_url('images/'.$data['podcast_image']),
            ];
        }
        return $jsonObj;
    }
    
    private function getBannerList($result){
        $jsonObj = [];
        if (empty($result)) {
           return $jsonObj; 
        }
        foreach ($result as $data) {
            $jsonObj[] = [
                'bid'           => $data['bid'],
                'banner_title'  => $data['banner_title'],
                'banner_info'   => $data['banner_info'],
                'banner_image'  => base_url('images/' . $data['banner_image'])
            ];
        }
        return $jsonObj;
    }
    
    private function getCountriesList($result){
        $jsonObj = [];
        if (empty($result)) {
           return $jsonObj; 
        }
        foreach ($result as $data) {
            $jsonObj[] = [
                'sid'           => $data['sid'],
                'countries_name'  => $data['countries_name'],
                'countries_image'  => base_url('images/' . $data['countries_image'])
            ];
        }
        return $jsonObj;
    }
    
    private function getRadioList($result){
        $jsonObj = [];
        if (empty($result)) {
           return $jsonObj; 
        }
        
        foreach ($result as $data) {
            $jsonObj[] = [
                'id'            => $data['id'],
                'cat_id'        => $data['cat_id'],
                'radio_title'   => $data['radio_title'],
                'radio_url'     => $data['radio_url'],
                'image'         => base_url('images/' . $data['radio_image']),
                'averageRating' => $data['rate_avg'],
                'totalRate'     => $data['total_rate'],
                'category_name' => $data['category_name'],
                'total_views'   => $data['total_views'],
                'is_premium'    => $data['isPremium']
            ];
        }
        return $jsonObj;
    }
    
    private function getRadioListSingle($result){
        $jsonObj = [];
        if (empty($result)) {
           return $jsonObj; 
        }
        
        foreach ($result as $data) {
            $jsonObj[] = [
                'id'            => $data['id'],
                'cat_id'        => $data['cat_id'],
                'radio_title'   => $data['radio_title'],
                'radio_url'     => $data['radio_url'],
                'image'         => base_url('images/' . $data['radio_image']),
                'averageRating' => $data['rate_avg'],
                'totalRate'     => $data['total_rate'],
                'category_name' => $data['category_name'],
                'total_views'   => $data['total_views'],
                'is_premium'    => $data['isPremium'],
                'radio_description'   => $data['radio_description'],
            ];
        }
        return $jsonObj;
    }
    
    private function getCategoryList($result){
        $jsonObj = [];
        if (empty($result)) {
           return $jsonObj; 
        }
        foreach ($result as $data) {
            $jsonObj[] = [
                'cid'           => $data['cid'],
                'category_name'  => $data['category_name'],
                'category_image'  => base_url('images/' . $data['category_image'])
            ];
        }
        return $jsonObj;
    }
    
    private function getPodcastsList($result){
        $jsonObj = [];
        if (empty($result)) {
           return $jsonObj; 
        }
        foreach ($result as $data) {
            $jsonObj[] = [
                'pid'           => $data['pid'],
                'podcast_name'  => $data['podcast_name'],
                'podcast_image'  => base_url('images/' . $data['podcast_image'])
            ];
        }
        return $jsonObj;
    }
    
    private function getNotificationList($result){
        $jsonObj = [];
        if (empty($result)) {
           return $jsonObj; 
        }
        foreach ($result as $data) {
            $jsonObj[] = [
                'id'                 => $data['id'],
                'notification_title' => $data['notification_title'],
                'notification_msg'   => $data['notification_msg'],
                'notification_on'    => $data['notification_on']
            ];
        }
        return $jsonObj;
    }
    
    private function updateActivityLog($user_id) {
        $logModel = new ActiveLogModel();
        $log = $logModel->where('user_id', $user_id)->first();
        $timestamp = strtotime(date('d-m-Y h:i:s A'));
        if (!$log) {
            $data_log = ['user_id' => $user_id, 'date_time' => $timestamp];
            $logModel->insert($data_log);
        } else {
            $logModel->where('user_id', $user_id)->set(['date_time' => $timestamp])->update();
        }
    }
}